layui.define(['element', 'api','utils'], function(exports) {
	"use strict";

	/**
	 * Button component
	 * */
	var MOD_NAME = 'publish',
		$ = layui.jquery,
        utils = layui.utils,
        api = layui.api,
        buttonId = 'run'
    ;

	var publish = function(opt) {
		this.option = opt;
	};

    function addDom(option){
        var dom = `
            <li class="layui-nav-item" >
                    <button id="${buttonId}" type="button" class="layui-btn-sm layui-btn-radius layui-btn-warm publish"  ><i class="layui-icon layui-icon-triangle-r">Publish</i></button>
            </li>
        `
        $(option.elem).append(dom);
    }

    /**
	 * Button start loading
	 * */
     publish.prototype.render = function(opt) {
		
		var option = {
			elem: opt.elem,
            api: opt.api,
            callback:opt.callback
		}

        addDom(option);

        $("#run").click(function(){
            let treeNodedata = utils.getTreeNodeData();

            //ajax 必须异步
            // var index = layer.load(0, {shade: false});
            var index = layer.load(1, {
                shade: [0.1,'#fff'] //0.1透明度的白色背景
            });

            let pushApi = utils.stringformat(option.api,treeNodedata);
            api.post({
                enableRootPath: true,
                url: pushApi,
                async: true,
                success: function(data){
                    layer.msg('操作成功');
                    layer.close(index);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    layer.close(index);
                    // debugger
                    layer.msg(XMLHttpRequest.responseJSON.msg);
                    // layer.msg(textStatus);
                    // 状态码
                    //  console.log(XMLHttpRequest.status);
                    // 状态
                    // console.log(XMLHttpRequest.readyState);
                    // 错误信息
                    // console.log(textStatus);
                }
            });
        });


        if(option.callback && option.callback.ready && typeof option.callback.ready === 'function'){
            option.callback.ready(option.elem, buttonId);
        }

        return new publish(option);
	}


    

    exports(MOD_NAME, new publish());
});
